package ciicos.service.impl;

import ciicos.entity.*;
import ciicos.mapper.LineQuestionMapper;
import ciicos.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import ciicos.util.RandomUtil;
import java.math.BigDecimal;
import cn.hutool.core.util.ObjectUtil;
import ciicos.permission.model.authorize.AuthorizeConditionModel;

import ciicos.util.GeneraterSwapUtil;
import ciicos.model.visiual.superQuery.ConditionJsonModel;
import ciicos.model.visiual.superQuery.SuperQueryJsonModel;
import ciicos.model.visiual.superQuery.SuperQueryConditionModel;


import ciicos.permission.service.AuthorizeService;


import java.lang.reflect.Field;
import com.baomidou.mybatisplus.annotation.TableField;
import java.util.stream.Collectors;
import ciicos.model.linequestion.*;










import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import java.text.SimpleDateFormat;
import ciicos.util.*;
import java.util.*;
import ciicos.base.model.filter.RuleInfo;
import ciicos.permission.util.GenUtil;
/**
 *
 * 题库管理
 * 版本： V3.2.0
 * 版权： 
 * 作者： 企业研发中心
 * 日期： 2025-10-07
 */
@Service
public class LineQuestionServiceImpl extends ServiceImpl<LineQuestionMapper, LineQuestionEntity> implements LineQuestionService{



        @Autowired
        private GeneraterSwapUtil generaterSwapUtil;

        @Autowired
        private UserProvider userProvider;

        @Autowired
        private AuthorizeService authorizeService;


    @Autowired
    private LineQuestionOptionsService lineQuestionOptionsService;




    @Override
    public List<LineQuestionEntity> getList(LineQuestionPagination lineQuestionPagination){
        return getTypeList(lineQuestionPagination,lineQuestionPagination.getDataType());
    }
    @Override
    public List<LineQuestionEntity> getTypeList(LineQuestionPagination lineQuestionPagination,String dataType){
        String userId=userProvider.get().getUserId();
        List<String> AllIdList =new ArrayList();
		List<List<String>> intersectionList =new ArrayList<>();
		int total=0;
		int lineQuestionNum =0;
        QueryWrapper<LineQuestionEntity> lineQuestionQueryWrapper=new QueryWrapper<>();
		int lineQuestionOptionsNum =0;
        QueryWrapper<LineQuestionOptionsEntity> lineQuestionOptionsQueryWrapper=new QueryWrapper<>();

//树形，异步父级查询条件
            long lineQuestionOptionscount = lineQuestionOptionsService.count();
		List<String> allSuperIDlist = new ArrayList<>();
		String superOp ="";
	if (ObjectUtil.isNotEmpty(lineQuestionPagination.getSuperQueryJson())){
		SuperQueryJsonModel superQueryJsonModel = JsonUtil.getJsonToBean(lineQuestionPagination.getSuperQueryJson(), SuperQueryJsonModel.class);
		String matchLogic = superQueryJsonModel.getMatchLogic();
		List<ConditionJsonModel> superQueryList = JsonUtil.getJsonToList(superQueryJsonModel.getConditionJson(), ConditionJsonModel.class);
		for (ConditionJsonModel conditionjson : superQueryList){
            Map<String, Object> map = JsonUtil.stringToMap(conditionjson.getAttr());
            Map<String, Object> configMap = JsonUtil.stringToMap(map.get("__config__").toString());
            String tableName = configMap.get("relationTable")!=null ? String.valueOf(configMap.get("relationTable")) : String.valueOf(configMap.get("tableName"));
		    if (map.get("multiple") != null) {
		        if (Boolean.valueOf(String.valueOf(map.get("multiple"))) && ObjectUtil.isNull(conditionjson.getFieldValue())) {
		            conditionjson.setFieldValue("[]");
		        }
		    }
            conditionjson.setTableName(tableName);
		}
		List<String> allSuperList = new ArrayList<>();
		List<List<String>> intersectionSuperList  = new ArrayList<>();



        int lineQuestionNum1 = 0;
        QueryWrapper<LineQuestionEntity> lineQuestionSuperWrapper = new QueryWrapper<>();
        lineQuestionNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(lineQuestionSuperWrapper,superQueryList,matchLogic,"line_question")
        ,new LineQuestionEntity(),lineQuestionNum1);
            if (lineQuestionNum1>0){
            List<String> lineQuestionList =this.list(lineQuestionSuperWrapper).stream().map(LineQuestionEntity::getId).collect(Collectors.toList());
            allSuperList.addAll(lineQuestionList);
            intersectionSuperList.add(lineQuestionList);
            }
        int lineQuestionOptionsNum1 = 0;
        QueryWrapper<LineQuestionOptionsEntity> lineQuestionOptionsSuperWrapper = new QueryWrapper<>();
        lineQuestionOptionsNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(lineQuestionOptionsSuperWrapper,superQueryList,matchLogic,"line_question_options")
        ,new LineQuestionOptionsEntity(),lineQuestionOptionsNum1);
            if (lineQuestionOptionsNum1>0 && lineQuestionOptionscount>0){

            List<String> lineQuestionOptionsList =lineQuestionOptionsService.list(lineQuestionOptionsSuperWrapper).stream().map(LineQuestionOptionsEntity::getQuestionid).collect(Collectors.toList());
            allSuperList.addAll(lineQuestionOptionsList);
            intersectionSuperList.add(lineQuestionOptionsList);
            }
		superOp = matchLogic;
		//and or
		if(matchLogic.equalsIgnoreCase("and")){
		    allSuperIDlist = generaterSwapUtil.getIntersection(intersectionSuperList);
		}else{
		    allSuperIDlist = allSuperList;
		}
    }
    boolean pcPermission = false;
    boolean appPermission = false;
    boolean	isPc = ServletUtil.getHeader("ciicos-origin").equals("pc");
    if(isPc && pcPermission){
		if (!userProvider.get().getIsAdministrator()){
			Object lineQuestionObj=authorizeService.getCondition(new AuthorizeConditionModel(lineQuestionQueryWrapper,lineQuestionPagination.getMenuId(),"line_question"));
            if (ObjectUtil.isEmpty(lineQuestionObj)){
                return new ArrayList<>();
            } else {
                lineQuestionQueryWrapper = (QueryWrapper<LineQuestionEntity>)lineQuestionObj;
                if( lineQuestionQueryWrapper.getExpression().getNormal().size()>0){
                    lineQuestionNum++;
                }
            }
			Object lineQuestionOptionsObj=authorizeService.getCondition(new AuthorizeConditionModel(lineQuestionOptionsQueryWrapper,lineQuestionPagination.getMenuId(),"line_question_options"));
            if (ObjectUtil.isEmpty(lineQuestionOptionsObj)){
                return new ArrayList<>();
            } else {
                lineQuestionOptionsQueryWrapper = (QueryWrapper<LineQuestionOptionsEntity>)lineQuestionOptionsObj;
                if( lineQuestionOptionsQueryWrapper.getExpression().getNormal().size()>0){
                    lineQuestionOptionsNum++;
                }
            }
        }
    }
    if(!isPc && appPermission){
		if (!userProvider.get().getIsAdministrator()){
			Object lineQuestionObj=authorizeService.getCondition(new AuthorizeConditionModel(lineQuestionQueryWrapper,lineQuestionPagination.getMenuId(),"line_question"));
            if (ObjectUtil.isEmpty(lineQuestionObj)){
                return new ArrayList<>();
            } else {
            lineQuestionQueryWrapper = (QueryWrapper<LineQuestionEntity>)lineQuestionObj;
				if( lineQuestionQueryWrapper.getExpression().getNormal().size()>0){
                     lineQuestionNum++;
				}
			}


			Object lineQuestionOptionsObj=authorizeService.getCondition(new AuthorizeConditionModel(lineQuestionOptionsQueryWrapper,lineQuestionPagination.getMenuId(),"line_question_options"));
            if (ObjectUtil.isEmpty(lineQuestionOptionsObj)){
                return new ArrayList<>();
            } else {
            lineQuestionOptionsQueryWrapper = (QueryWrapper<LineQuestionOptionsEntity>)lineQuestionOptionsObj;
				if( lineQuestionOptionsQueryWrapper.getExpression().getNormal().size()>0){
                     lineQuestionOptionsNum++;
				}
			}


		}
    }



        if(isPc){
			if(ObjectUtil.isNotEmpty(lineQuestionPagination.getType())){
            lineQuestionNum++;

                            List<String> idList = new ArrayList<>();
                            try {
                                String[][] type = JsonUtil.getJsonToBean(lineQuestionPagination.getType(),String[][].class);
                                for(int i=0;i<type.length;i++){
                                    if(type[i].length>0){
                                        idList.add(type[i][type[i].length-1]);
                                    }
                                }
                            }catch (Exception e1){
                                try {
                                    List<String> type = JsonUtil.getJsonToList(lineQuestionPagination.getType(),String.class);
                                    if(type.size()>0){
                                        idList.add(type.get(type.size()-1));
                                    }
                                }catch (Exception e2){
                                    idList.add(String.valueOf(lineQuestionPagination.getType()));
                                }
                            }
                        lineQuestionQueryWrapper.lambda().and(t->{
                            idList.forEach(tt->{
                                t.like(LineQuestionEntity::getType, tt).or();
                                });
                            });

                    }

			if(ObjectUtil.isNotEmpty(lineQuestionPagination.getQuestiontype())){
            lineQuestionNum++;

                        lineQuestionQueryWrapper.lambda().eq(LineQuestionEntity::getQuestiontype,lineQuestionPagination.getQuestiontype());

                    }

			if(ObjectUtil.isNotEmpty(lineQuestionPagination.getQuestion())){
            lineQuestionNum++;

                    lineQuestionQueryWrapper.lambda().like(LineQuestionEntity::getQuestion,lineQuestionPagination.getQuestion());

                    }

        }
            if(lineQuestionOptionsNum>0){
            List<String> lineQuestionOptionsIdList = lineQuestionOptionsService.list(lineQuestionOptionsQueryWrapper).stream().filter(t->StringUtil.isNotEmpty(t.getQuestionid())).map(t->t.getQuestionid()).collect(Collectors.toList());
			long count = lineQuestionOptionsService.count();
            if (count>0){
				intersectionList.add(lineQuestionOptionsIdList);
            }
            AllIdList.addAll(lineQuestionOptionsIdList);
            }
            total+=lineQuestionOptionsNum;
		List<String> intersection = generaterSwapUtil.getIntersection(intersectionList);
		if (total>0){
		if (intersection.size()==0){
		    intersection.add("jnpfNullList");
		}
         lineQuestionQueryWrapper.lambda().in(LineQuestionEntity::getId, intersection);
		}
        //是否有高级查询
		if (StringUtil.isNotEmpty(superOp)){
		    if (allSuperIDlist.size()==0){
		        allSuperIDlist.add("jnpfNullList");
		    }
		List<String> finalAllSuperIDlist = allSuperIDlist;
            lineQuestionQueryWrapper.lambda().and(t->t.in(LineQuestionEntity::getId, finalAllSuperIDlist));
		}


        //排序
        if(StringUtil.isEmpty(lineQuestionPagination.getSidx())){
        lineQuestionQueryWrapper.lambda().orderByDesc(LineQuestionEntity::getId);
        }else{
            try {
            	String sidx = lineQuestionPagination.getSidx();
                LineQuestionEntity lineQuestionEntity = new LineQuestionEntity();
				Field declaredField = lineQuestionEntity.getClass().getDeclaredField(sidx);
				declaredField.setAccessible(true);
				String value = declaredField.getAnnotation(TableField.class).value();
                 lineQuestionQueryWrapper="asc".equals(lineQuestionPagination.getSort().toLowerCase())?lineQuestionQueryWrapper.orderByAsc(value):lineQuestionQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
        // 过滤条件

        if("0".equals(dataType)){
            if((total>0 && AllIdList.size()>0) || total==0){
                Page<LineQuestionEntity> page=new Page<>(lineQuestionPagination.getCurrentPage(), lineQuestionPagination.getPageSize());
                IPage<LineQuestionEntity> userIPage=this.page(page, lineQuestionQueryWrapper);
                return lineQuestionPagination.setData(userIPage.getRecords(),userIPage.getTotal());
            }else{
                List<LineQuestionEntity> list = new ArrayList();
                return lineQuestionPagination.setData(list, list.size());
            }
        }else{
            return this.list(lineQuestionQueryWrapper);
        }
    }
    public QueryWrapper wrapperHandle(QueryWrapper<?> wrapper, String id, Class<?> aClass, String type,String tableName) {
        try{
            // 避免空and
            wrapper.apply(" 1=1 ");
            List<RuleInfo> ruleInfos = generaterSwapUtil.getFilterCondition(id);
            for (RuleInfo info : ruleInfos){
                String field=info.getField();
                if ("main".equals(type) && field.contains("-")) {
                    continue;
                }
                if ("main".equals(type) && field.contains("_jnpf_" )) {
                    continue;
                }
                if ("sub".equals(type) && !field.contains("-")) {
                    continue;
                }
                if("sub-jnpf".equals(type) && !field.contains("_jnpf_" )){
                    continue;
                }
                String fieldName = field ;
                String table = "";
                if(field.contains("-")){
                    fieldName= field.split("-")[1];
                }
                if(field.contains("_jnpf_" )){
                    fieldName = field.split("_jnpf_" )[1];
                    table = field.split("_jnpf_" )[0];
                    table = table.replace("jnpf_","");
                }
                if("sub-jnpf".equals(type) && !tableName.equals(table)){
                    continue;
                }
                Field declaredField=aClass.getDeclaredField(fieldName);
                declaredField.setAccessible(true);
                String fieldDb=declaredField.getAnnotation(TableField.class).value();
                GenUtil genUtil=JsonUtil.getJsonToBean(info,GenUtil.class);
                genUtil.solveValue(wrapper, fieldDb);
            }
            return wrapper;
        }catch (Exception e){
            return  wrapper;
        }
    }

    @Override
    public LineQuestionEntity getInfo(String id){
        QueryWrapper<LineQuestionEntity> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(LineQuestionEntity::getId,id);
        return this.getOne(queryWrapper);
    }

    @Override
    public void create(LineQuestionEntity entity){
        this.save(entity);
    }

    @Override
    public boolean update(String id, LineQuestionEntity entity){
        return this.updateById(entity);
    }
    @Override
    public void delete(LineQuestionEntity entity){
        if(entity!=null){
            this.removeById(entity.getId());
        }
    }
    //子表方法
		@Override
		public List<LineQuestionOptionsEntity> getLineQuestionOptionsList(String id,LineQuestionPagination lineQuestionPagination){
				QueryWrapper<LineQuestionOptionsEntity> queryWrapper = new QueryWrapper<>();
				queryWrapper = lineQuestionOptionsService.getChild(lineQuestionPagination,queryWrapper);
				queryWrapper.lambda().eq(LineQuestionOptionsEntity::getQuestionid, id);
                this.wrapperHandle(queryWrapper, lineQuestionPagination.getModuleId(),LineQuestionOptionsEntity.class,"sub","lineQuestionOptions");
				return lineQuestionOptionsService.list(queryWrapper);
				}

		@Override
		public List<LineQuestionOptionsEntity> getLineQuestionOptionsList(String id){
				QueryWrapper<LineQuestionOptionsEntity> queryWrapper = new QueryWrapper<>();
				queryWrapper.lambda().eq(LineQuestionOptionsEntity::getQuestionid, id);
				return lineQuestionOptionsService.list(queryWrapper);
        }

    //列表子表数据方法



    //验证表单唯一字段
    @Override
    public String checkForm(LineQuestionForm form,int i) {
        int total = 0;
		boolean isUp =StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
		String id="";
		String countRecover = "";
		if (isUp){
			 id = form.getId();
		}
				 if (form.getLinequestionoptionsList()!=null){
         }

        return countRecover;
    }


}
